<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]"
             width="600px">
    <el-form ref="dataForm" label-position="left" label-width="90px" style='width: 400px; margin-left:50px;'
             :rules="rules"
             :model="orgForm"
             size="mini">
      <el-form-item label="机构名称" prop="nameZh">
        <el-input v-model="orgForm.nameZh"></el-input>
      </el-form-item>
      <el-form-item label="编码" prop="swiftcode">
        <el-input v-model="orgForm.swiftcode"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="addr">
        <el-input v-model="orgForm.addr"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="tel">
        <el-input v-model="orgForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="orgForm.contactPerson"></el-input>
      </el-form-item>

      <!--<el-form-item label="父机构" prop="parentOrgId" >-->
      <!--<el-select style="width: 140px" class="filter-item" v-model="orgForm.parentOrgId" >-->
      <!--<el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" >-->
      <!--</el-option >-->
      <!--</el-select >-->
      <!--</el-form-item >-->

      <el-form-item label="父机构" prop="parentOrgId">
        <treeselect placeholder="请选择父级机构" v-model="orgForm.parentOrgId"
                    :multiple="false"
                    :load-options="loadOrgsOptions"
                    :options="options"/>
      </el-form-item>

      <el-form-item label="选择角色" prop="roleId">
        <treeselect placeholder="请选择角色" :multiple="true" value-consists-of="LEAF_PRIORITY"
                    :disable-branch-nodes="true" v-model="orgForm.roleIds" :load-options="loadRolesOptions"
                    value-format="object" :options="groupslist"/>
      </el-form-item>

      <!--<el-form-item label="选择角色" prop="roleIds" >-->
      <!--<el-select style="width: 140px" class="filter-item" v-model="orgForm.roleIds" >-->
      <!--<el-option v-for="item in options" :key="item.key" :label="item.label" :value="item.key" >-->
      <!--</el-option >-->
      <!--</el-select >-->
      <!--</el-form-item >-->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
      <el-button size="mini" v-if="dialogStatus==='create'" type="primary" @click="handleSubmit">确定</el-button>
      <el-button size="mini" v-if="dialogStatus==='update'" type="primary" @click="submitSave">保存</el-button>
    </div>
  </el-dialog>
</template>


<script>
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { addOrg, updateOrg, getOrgById } from '@/api/orgs'
  import{ modifyObj, resetDataForm, covertArrParams } from '@/utils/tools'
  import { getRoleGroupList, getRolesList } from '@/api/roles'
  import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

  export default {
    name: 'newOrgDialog',
    components: {Treeselect},
    props: {
      orgOptions: {
        type: Array,
        default: []
      }
    },
    computed: {
      options(){
        return modifyObj(this.orgOptions)
      }
    },
    data(){
      return {
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改机构',
          create: '新建机构'
        },
        rules: {
          nameZh: [{required: true, message: '请填写机构名称', trigger: 'blur'}]
        },
        orgForm: {
          id: null,
          nameZh: null,
          addr: null,
          tel: null,
          swiftcode: null,
          contactPerson: null,
          roleIds: [],
          parentOrgId: null
        },
        groupslist: []
      }
    },
    methods: {
      loadOrgsOptions({action, parentNode, callback, id}){
        callback()
      },
      loadRolesOptions({action, parentNode, callback, id}){
        if (action === LOAD_CHILDREN_OPTIONS) {
          let _arr = []
          getRolesList({parentId: parentNode.id, pageSize: 9999}).then(res => {
            res = res.data
            if (res.data.dataList !== '') {
              res.data.dataList.forEach(item => {
                _arr.push({id: item.id, label: parentNode.label + '-' + item.name})
              })
            }
            parentNode.children = _arr
            callback(null, _arr)
          })

        }
      },
      getRoleGroupList(){
        getRoleGroupList({pageSize: 9999}).then(res => {
          res = res.data
          if (res.data.dataList !== null || res.data.dataList !== '') {
            res.data.dataList.forEach(item => {
              item.children = null
              item.label = item.name
            })
          }
          this.groupslist = []
          setTimeout(() => {
            this.groupslist = res.data.dataList
          }, 50)
        })
      },
      handleCreate() {
        this.getRoleGroupList()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.orgForm.roleIds = []
          resetDataForm(this.$refs['dataForm'])
          this.getRoleGroupList()
        })
      },
      handleEdit(id){
        this.dialogStatus = 'update'
        this.dialogFormVisible = true;
        this.orgForm.id = id
        this.$nextTick(() => {
          this.getRoleGroupList()
          getOrgById({id: id}).then(res => {
            res = res.data
            const {nameZh, swiftcode, addr, tel, contactPerson, roles, parentOrgId} = res.data
            this.orgForm = {
              id, nameZh, addr, tel, swiftcode, contactPerson
            }
            if (parentOrgId !== null && parentOrgId !== 0) {
              this.orgForm.parentOrgId = parentOrgId
            }
            let rolesArr = []
            if (roles !== null && roles !== '') {
              roles.forEach(item => {
                rolesArr.push({label: item.parentRoleName + '-' + item.roleName, id: item.roleId})
              })
            }
            if (rolesArr.length > 0) {
              this.orgForm.roleIds = rolesArr
            }
          })
        })
      },
      handleSubmit(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let _roleIdsArr = [], _paramObj = this.orgForm
            _paramObj.roleIds.forEach(item => {
              _roleIdsArr.push(item.id)
            })
            _paramObj = Object.assign({}, _paramObj, {roleIds: _roleIdsArr.join(',')})
            addOrg(_paramObj).then(res => {
              res = res.data
              this.$message({showClose: true, message: '创建成功', type: 'success'});
              this.dialogFormVisible = false
              this.$emit('submited-menu', res)
            })
          }
        })
      },
      submitSave(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.orgForm.parentOrgId === this.orgForm.id) {
              this.$message({showClose: true, message: '不能选择当前机构作为父机构', type: 'error'});
              return false
            }
            let _roleIdsArr = [], _paramObj = this.orgForm
            _paramObj.roleIds.forEach(item => {
              _roleIdsArr.push(item.id)
            })
            _paramObj = Object.assign({}, _paramObj, {roleIds: _roleIdsArr.join(',')})
            updateOrg(_paramObj).then(res => {
              res = res.data
              this.$message({showClose: true, message: '修改成功', type: 'success'});
              this.dialogFormVisible = false
              this.$emit('submited-menu', res)
            })
          }
        })
      }
    }
  }
</script>
